//
//  NutritionHealthDetailViewCtl.swift
//  YLH
//
//  Created by qinjiangtao on 2024/1/21.
//  营养健康详情页

import UIKit

class NutritionHealthDetailViewCtl: UIViewController {
    
    var model = NutritionHealthModel()
    
    /// 重量
    private var weightTextF = UITextField()
    /// 容量
    private var capacityTextF = UITextField()
    /// 大小
    private var sizeTextF = UITextField()
    var grids = [[Grid]]()
    let tabulationView = TabulationView()
    let reuseIdentifier = "text"
    /// 行数
    var rowCount = 19
    /// 列数
    let colCount = 4
    
    private var leftTitleArr = [String]()
    private var centerTitleArr = [String]()
    private var rightTitleArr = [String]()
    private var percentageTitleArr = [String]()
    private var setParam = [String: String]()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        title = model.name
        
        addUI()
        generateData()
        getData()
    }
    
    
    
    private func addUI() {
        let rightBtn = UIButton().then {
            $0.frame = CGRect(x: 0, y: 0, width: 44, height: 44)
            $0.titleLabel?.font = FONT(ofSize: 12)
            $0.setTitle("保存", for: .normal)
            $0.setTitleColor(Color333333, for: .normal)
            $0.addTarget(self, action: #selector(rightBtnClick), for: .touchUpInside)
        }
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(customView: rightBtn)
        
        leftTitleArr = ["能量(千卡)", "蛋白质(克)", "碳水化合物(克)", "脂肪(克)", "膳食纤维(克)", "糖(克)", "饱和脂肪(克)", "反式脂肪(克)", "胆固醇(毫克)", "钙(毫克)", "铜(毫克)", "铁(毫克)", "镁(毫克)", "锰(毫克)", "磷(毫克)", "钾(毫克)", "钠(毫克)", "锌(毫克)", "维生素C(毫克)"]
        centerTitleArr = ["Energy(kcal)", "Protein(g)", "Carbohydrates(g)", "Fat(g)", "Dietary Fiber(g)", "Sugar(g)", "Saturated fat(g)", "Trans fat(g)", "Cholesterol(mg)", "Calcium(mg)", "Copper (mg)", "lron(mg)", "Magnesium (mg)", "Manganese（mg)", "Phosphorus（mg)", "Potassium（mg)","Sodium（mg)", "Zinc（mg)", "Vitamin Cha(mg)"]
        rowCount = leftTitleArr.count
        
            navigationController?.navigationBar.titleTextAttributes = [NSAttributedString.Key.foregroundColor : Color333333]
        
        self.view.addGradientColor(fromColors: [ColorWithStr("#FFB2B5").cgColor, ColorWithStr("#FCDFE0").cgColor, ColorWithStr("#FFFBFB").cgColor], locationArr: [0, 0.5, 1.0], with: .topToBottom)
        
        
        addSetingView()
        
        let cellW = (SCREEN_WIDTH - 30) / 3
        let titleL6 = UILabel().then({
            $0.frame = CGRect(x: 15, y: sizeTextF.bottom + 20, width: cellW, height: 40)
            $0.backgroundColor = MainColor
            $0.text = "营养资料"
            $0.textAlignment = .center
            $0.textColor = .white
            $0.font = SYSFONTBOLD(ofSize: 15)
        })
        view.addSubview(titleL6)
        let titleL7 = UILabel().then({
            $0.frame = CGRect(x: titleL6.right, y: sizeTextF.bottom + 20, width: cellW, height: 40)
            $0.backgroundColor = MainColor
//            $0.text = "Name"
            $0.textAlignment = .center
            $0.textColor = .white
            $0.font = SYSFONTBOLD(ofSize: 15)
        })
        view.addSubview(titleL7)
        let titleL8 = UILabel().then({
//            $0.frame = CGRect(x: titleL7.right, y: sizeTextF.bottom + 20, width: cellW / 2, height: 40)
            $0.frame = CGRect(x: titleL6.right, y: sizeTextF.bottom + 20, width: cellW * 2, height: 40)
            $0.backgroundColor = MainColor
            $0.text = model.name
            $0.textAlignment = .center
            $0.textColor = .white
            $0.font = SYSFONTBOLD(ofSize: 15)
        })
        view.addSubview(titleL8)
        
        let titleL9 = UILabel().then({
            $0.frame = CGRect(x: titleL8.right, y: sizeTextF.bottom + 20, width: cellW / 2, height: 40)
            $0.backgroundColor = MainColor
//            $0.text = "百分比"
            $0.textAlignment = .center
            $0.textColor = .white
            $0.font = SYSFONTBOLD(ofSize: 15)
        })
//        view.addSubview(titleL9)
        
        addMianRongJianKangUI()
    }
    
    private func addSetingView() {
        
        
        let arr = model.button_on_or_off.components(separatedBy: ",")
        let titleArr = ["食物重量(克)", "食物容量(毫升)", "食物手掌大小"]
        var minX = NAV_HEIGHT + 5
        for (index, titleStr) in titleArr.enumerated() {
            let titleL5 = UILabel().then({
                $0.frame = CGRect(x: 30, y: minX, width: 100, height: 34)
                $0.text = titleStr//"食物总重量(克）"
                $0.textAlignment = .right
                $0.textColor = Color333333
                $0.font = SYSFONT(ofSize: 12)
            })
            view.addSubview(titleL5)
            
            let leftView1 = UIView()
            leftView1.frame = CGRect(x: 0, y: 0, width: 10, height: 0)
            let TextF = UITextField().then {
                $0.frame = CGRect(x: titleL5.right + 10, y: titleL5.top, width: SCREEN_WIDTH - 250, height: 34)
                $0.font = SYSFONT(ofSize: 14)
                $0.placeholder = ""
                $0.text = ""
                $0.delegate = self
                $0.keyboardType = .numberPad
                $0.backgroundColor = ColorEEEEEE
                $0.leftView = leftView1
                $0.leftViewMode = .always
                $0.addRoundedCorners(withRadius: 5)
            }
            view.addSubview(TextF)
            
            if index == 0 {
                weightTextF = TextF
                let weight = model.nutrtion.weight
                if arr.count == 3 && arr[0] == "1" && weight != "" && weight != "0" {
                    weightTextF.text = weight
                } else {
                    weightTextF.text = ""
                }
            } else if index == 1 {
                capacityTextF = TextF
                if arr.count == 3 {
                    capacityTextF.text = arr[1] == "1" ? model.nutrtion.capacity : ""
                } else {
                    capacityTextF.text = ""
                }
            } else if index == 2 {
                sizeTextF = TextF
                let palm_size = model.nutrtion.palm_size
                if arr.count == 3 && arr[2]  == "1" && palm_size != "" && palm_size != "0" {
                    sizeTextF.text = model.nutrtion.palm_size
                } else {
                    sizeTextF.text = ""
                }
            }
            
            let setBtn = UIButton().then {
                $0.frame = CGRect(x: SCREEN_WIDTH - 100, y: titleL5.top, width: 66, height: 34)
                $0.backgroundColor = MainColor
                $0.tag = index + 1
                $0.titleLabel?.font = SYSFONT(ofSize: 13)
                $0.setTitle("设置", for: .normal)
                $0.setTitleColor(.white, for: .normal)
                $0.addRoundedCorners(withRadius: 5)
                $0.addTarget(self, action: #selector(setBtnClick(btn:)), for: .touchUpInside)
            }
            view.addSubview(setBtn)
            
            minX = titleL5.bottom + 10
        }
    }
    
    @objc private func rightBtnClick() {
        QINetworkManager.requestJson(urlStr: "/Project/healthNutrition", parameters: setParam) { json in
            let result = json["result"]
            self.setRightTitleArr(json: result)
        }
    }
    
    private func getData() {
        QINetworkManager.requestJson(urlStr: "/Project/healthDeail", method: .get, parameters: ["id": model.id]) { json in
            print(json)
            let result = json["result"]
            self.setRightTitleArr(json: result)
        }
        
    }
    
    /// 设置食物克数
    @objc private func setBtnClick(btn: UIButton) {
        let weightStr = weightTextF.text ?? ""
        let capacityStr = capacityTextF.text ?? ""
        let palm_sizeStr = sizeTextF.text ?? ""
        setParam = [
            "id": model.id,
            "type": "\(btn.tag)",     //1：重量 2：容量 3：手掌大小
            "weight": weightStr,
            "capacity": capacityStr,
            "palm_size": palm_sizeStr
        ]
        QINetworkManager.requestJson(urlStr: "/Project/healthDetailNutrition", parameters: setParam) { json in
            self.setRightTitleArr(json: json)
        }
    }
    
    private func setRightTitleArr(json: JSON) {
        self.rightTitleArr.removeAll()
//        self.rightTitleArr.append(json["energy_information"].stringValue)
//        self.rightTitleArr.append(json["protein_information"].stringValue)
//        self.rightTitleArr.append(json["carbohydrates_information"].stringValue)
//        self.rightTitleArr.append(json["fat_information"].stringValue)
//        self.rightTitleArr.append(json["dietary_fiber_information"].stringValue)
//        self.rightTitleArr.append(json["sugar_information"].stringValue)
//        self.rightTitleArr.append(json["saturated_information"].stringValue)
//        self.rightTitleArr.append(json["trans_fat_information"].stringValue)
//        self.rightTitleArr.append(json["cholesterol_information"].stringValue)
//        self.rightTitleArr.append(json["calcium_information"].stringValue)
//        self.rightTitleArr.append(json["copper_information"].stringValue)
//        self.rightTitleArr.append(json["iron_information"].stringValue)
//        self.rightTitleArr.append(json["magnesium_information"].stringValue)
//        self.rightTitleArr.append(json["manganese_information"].stringValue)
//        self.rightTitleArr.append(json["phosphorus_information"].stringValue)
//        self.rightTitleArr.append(json["potassium_information"].stringValue)
//        self.rightTitleArr.append(json["sodium_information"].stringValue)
//        self.rightTitleArr.append(json["zinc_information"].stringValue)
//        self.rightTitleArr.append(json["vitamin_c_information"].stringValue)
        
        
        self.percentageTitleArr.removeAll()
//        self.percentageTitleArr.append(json["energy_proportion"].stringValue)
//        self.percentageTitleArr.append(json["protein_proportion"].stringValue)
//        self.percentageTitleArr.append(json["carbohydrates_proportion"].stringValue)
//        self.percentageTitleArr.append(json["fat_proportion"].stringValue)
//        self.percentageTitleArr.append(json["dietary_fiber_proportion"].stringValue)
//        self.percentageTitleArr.append(json["sugar_proportion"].stringValue)
//        self.percentageTitleArr.append(json["saturated_proportion"].stringValue)
//        self.percentageTitleArr.append(json["trans_fat_proportion"].stringValue)
//        self.percentageTitleArr.append(json["cholesterol_proportion"].stringValue)
//        self.percentageTitleArr.append(json["calcium_proportion"].stringValue)
//        self.percentageTitleArr.append(json["copper_proportion"].stringValue)
//        self.percentageTitleArr.append(json["iron_proportion"].stringValue)
//        self.percentageTitleArr.append(json["magnesium_proportion"].stringValue)
//        self.percentageTitleArr.append(json["manganese_proportion"].stringValue)
//        self.percentageTitleArr.append(json["phosphorus_proportion"].stringValue)
//        self.percentageTitleArr.append(json["potassium_proportion"].stringValue)
//        self.percentageTitleArr.append(json["sodium_proportion"].stringValue)
//        self.percentageTitleArr.append(json["iron_proportion"].stringValue)
//        self.percentageTitleArr.append(json["vitamin_c_proportion"].stringValue)
        
        processingData(key: "energy", json: json)
        processingData(key: "protein", json: json)
        processingData(key: "carbohydrates", json: json)
        processingData(key: "fat", json: json)
        processingData(key: "dietary_fiber", json: json)
        processingData(key: "sugar", json: json)
        processingData(key: "saturated", json: json)
        processingData(key: "trans_fat", json: json)
        processingData(key: "cholesterol", json: json)
        processingData(key: "calcium", json: json)
        processingData(key: "copper", json: json)
        processingData(key: "iron", json: json)
        processingData(key: "magnesium", json: json)
        processingData(key: "manganese", json: json)
        processingData(key: "phosphorus", json: json)
        processingData(key: "potassium", json: json)
        processingData(key: "sodium", json: json)
        processingData(key: "iron", json: json)
        processingData(key: "vitamin_c", json: json)
        
        self.generateData()
    }
    
    private func processingData(key: String, json: JSON) {
        let information = json["\(key)_information"].stringValue
        if information == "-1" {
            self.rightTitleArr.append("-1")
        } else {
            self.rightTitleArr.append(json[key].stringValue)
        }
        self.percentageTitleArr.append(json["\(key)_proportion"].stringValue)
    }
   
}

extension NutritionHealthDetailViewCtl: TabulationViewDataSource, UITextFieldDelegate {
    
    func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
        if textField == weightTextF {
            capacityTextF.text = ""
            sizeTextF.text = ""
        } else if textField == capacityTextF {
            weightTextF.text = ""
            sizeTextF.text = ""
        } else if textField == sizeTextF {
            capacityTextF.text = ""
            weightTextF.text = ""
        }
        return true
    }
    
    private func addMianRongJianKangUI() {
        
        tabulationView.frame = CGRect(x: 15, y: sizeTextF.bottom + 60, width: SCREEN_WIDTH - 30, height: SCREEN_HEIGHT - sizeTextF.bottom - 80)
        tabulationView.backgroundColor = MainColor
        tabulationView.register(TextTabulationViewCell.self, forCellReuseIdentifier: reuseIdentifier)
        tabulationView.dataSource = self
        view.addSubview(tabulationView)
        
    }
    
    func generateData() {
        grids.removeAll()
        for row in 0..<rowCount {
            var rowGrids = [Grid]()
            for col in 0..<colCount {
                var text = ""
                if col == 0 {
                    text = leftTitleArr[row]
                } else if col == 1 {
                    text = centerTitleArr[row]
                } else if col == 2 {
                    text = rightTitleArr.count > row ? rightTitleArr[row] : ""
                } else if col == 3 {
                    text = percentageTitleArr.count > row ? "\(percentageTitleArr[row])%" : ""
                }
                let grid = Grid(content: text)
                rowGrids.append(grid)
            }
            grids.append(rowGrids)
        }
        tabulationView.reloadData()
    }
    
    func numberOfRows(in tabulationView: TabulationView) -> Int {
        return rowCount
    }
    
    func numberOfCols(in tabulationView: TabulationView) -> Int {
        return colCount
    }
    
    //列宽
    func tabulationView(_ tabulationView: TabulationView, lengthForCol col: Int) -> CGFloat {
        if col < 2 {
            return (SCREEN_WIDTH - 30) / 3 - 1
        } else {
            return (SCREEN_WIDTH - 30) / 6
        }
    }
    
    func tabulationView(_ tabulationView: TabulationView, cellForIndexPath indexPath: TabIndexPath) -> TabulationViewCell? {
        
        guard let cell = tabulationView.dequeueReusableCell(withIdentifier: reuseIdentifier, for: indexPath) as? TextTabulationViewCell else {
            return nil
        }
        guard grids.count > indexPath.row else {
            return cell
        }
        let rowGrids = grids[indexPath.row]
        guard rowGrids.count > indexPath.col else {
            return cell
        }
        let grid = rowGrids[indexPath.col]
        cell.loadGrid(grid)
        return cell
    }
}
